#!/usr/bin/env python

import numpy as np
import os, serial,time,socket,sys,json
from meas_data import meas_data
# import the server implementation
# import ADC
sensor="veml6070"
pathname = os.path.dirname(sys.argv[0])        
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

parameter={"device":socket.gethostname(),"deviceid":"FF","mean_count":5,"ring_length":10,"wait":0.5,"cycle":10,"check_last":15,"check_last_shrinking":0.9,"gpg_keyid":"","digits":3,"store_dir":"/home/pi/log/","multiplicator":1000,"sensor":"VEML6070","sigma":3}
for n in parameter:
  if n in log_conf:
    parameter[n]=log_conf[n]

bveml=False
if sensor in log_conf:
  bveml=True
  if "enable" in log_conf[sensor]:
    if log_conf[sensor]['enable'] == 0:
      bveml=False
  if bveml:
    import veml6070
    parameter["i2c"]=1
    if "port" in log_conf[sensor]:
      parameter["i2c"]=int(log_conf[sensor]['port'])
    try:
      veml = veml6070.Veml6070(i2c_bus=parameter["i2c"])
    except:
      bveml=False
    else:
      tsl_sigma=parameter['sigma']
      for n in parameter:
        if n in log_conf:
          parameter[n]=log_conf[n]
      if "sigma" in log_conf[sensor]:
        parameter['sigma']=int(log_conf[sensor]['sigma'])
        if parameter['sigma'] < 1:
          parameter['sigma']=1
      parameter["var_name"]="uv"
      tsl_data=meas_data(parameter)
      bmqtt=False
      if "mqtt" in log_conf:
        bmqtt=True
        lcmq=log_conf['mqtt']
        mbroker=""
        if 'broker' in lcmq:
          mbroker=lcmq['broker']
        else:
          bmqtt=False
        mport=1883
        if 'port' in lcmq:
          mport=lcmq['port']
        if bmqtt:
          tsl_data.set_mqtt(broker=mbroker,port=mport)
      if "sqlserver" in log_conf:
        hostname="localhost"
        port=8080
        tsl_data.set_sql(host=hostname,port=port)
      if "opensensemap" in log_conf[sensor]:
        osm=log_conf['veml6070']['opensensemap']
        if "sensebox_id" in osm:
          sid=osm['sensebox_id']
          if "sensors" in osm:
            if "uv" in osm['sensors']:
              tsl_data.set_sensebox(sid,osm['sensors']['uv'])


if bveml:
  while True:
  
  # read bme280 (temperature, humidity, pressure)
    veml.set_integration_time(veml6070.INTEGRATIONTIME_1T)
    tsl_data.append(veml.get_uva_light_intensity())
    time.sleep(parameter['wait'])


# close the client
print("done")
